//
//  YYJ_NetRequest.m
//  miaoxiaqianbao
//
//  Created by Lonely丶晏袁杰 on 2018/10/9.
//  Copyright © 2018年 Lonely`yyj. All rights reserved.
//

#import "YYJ_NetRequest.h"
#import <AFNetworking/AFNetworking.h>
#import "AFNetworkActivityIndicatorManager.h"
@implementation YYJ_NetRequest

static YYJ_NetRequest *_instance;
// 为了使实例易于外界访问 我们一般提供一个类方法
// 类方法命名规范 share类名|default类名|类名
+(instancetype)shareNetRequest{
    return [[self alloc]init];
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}
// 为了严谨，也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _instance;
}
#if __has_feature(objc_arc)
//如果是ARC，那么就执行这里的代码1
#else
-(oneway void)release{

}
-(instancetype)retain{
    return _instance;
}
-(NSUInteger)retainCount{
    return MAXFLOAT;
}
#endif
static AFHTTPSessionManager * manager = nil;
-(AFHTTPSessionManager*)creatAFwithURL:(NSString*)kURL{
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        //#warning 可根据具体情况进行设置
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        //允许非权威机构颁发的证书
        manager.securityPolicy.allowInvalidCertificates = YES;
        //也不验证域名一致性
        manager.securityPolicy.validatesDomainName = NO;
        /**设置请求超时时间*/
        manager.requestSerializer.timeoutInterval = 60;
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        /**设置可接受的类型*/
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html", nil ,nil]];

    });
    //关闭缓存避免干扰测试
    manager.requestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    if ([YYJ_UserProfileModel sharedUserProfile].token.length>0) {
//        [_kBaseData setObject:[YYJ_UserProfileModel sharedUserProfile].token forKey:@"token"];
        [manager.requestSerializer setValue:[YYJ_UserProfileModel sharedUserProfile].token forHTTPHeaderField:@"token"];
    }
    return manager;
}


#pragma mark get 和post 带缓存的请求
/**
 *  网络请求的实例方法 - (带缓存)
 *  @param type             get / post
 *  @param urlString        请求的地址
 *  @param paraments        请求的参数
 *  @param jsonCache        本地缓存的回调（如果存在的话）
 *  @param successBlock     请求成功的回调
 *  @param failureBlock     请求失败的回调
 *  @param progress         上传的进度
 */
-(void)requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:(id)paraments jsonCacheBlock:(requestCache)jsonCache withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock progress:(downloadProgress)progress{
//    urlString = [NSURL isChinese:urlString];
    AFHTTPSessionManager * kAF =[self creatAFwithURL:urlString];
    switch (type) {
        case HttpRequestTypeGet:
        {
            [kAF GET:urlString parameters:paraments headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if([[responseObject class] isSubclassOfClass:[NSData class]]){
                    
                    responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                }
                NSDictionary *kDataDict = responseObject;
                NSString *err_code;
                if ([[kDataDict objectForKey:@"code"] isKindOfClass:[NSNumber class]]) {
                    err_code = [[kDataDict objectForKey:@"code"] stringValue];
                }else if([[kDataDict objectForKey:@"code"] isKindOfClass:[NSArray class]]){
                    err_code = [[kDataDict objectForKey:@"code"] firstObject];
                }else{
                    err_code = [kDataDict objectForKey:@"code"];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([err_code intValue]==400) {
                        //                        [self loginOut];
                        if ([[kDataDict objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                            if ([[[[kDataDict objectForKey:@"data"] objectForKey:@"code"] stringValue] isEqualToString:@"10100"]) {
                                [self loginOut];
                            }else if(successBlock){
                                successBlock(responseObject);
                            }
                        }else if(successBlock){
                            successBlock(responseObject);
                        }
                    }else if ([err_code intValue]==401){//需要更新
                        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"需要更新才能继续使用" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *kCancel = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            //8、itms-apps:// 开头
                            NSString *urlStr = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id%@", APPID];
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                        }];
                        UIAlertAction *kSend = [UIAlertAction actionWithTitle:@"稍后再去" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        }];
                        [kCancel setValue:APPMianColor forKey:@"_titleTextColor"];
                        [kSend setValue:APPMianColor forKey:@"_titleTextColor"];
                        
                        [alertVc addAction:kCancel];
                        [[YYJ_PublicClass getCurrentVC] presentViewController:alertVc animated:YES completion:nil];
                    }else if(successBlock){
                        successBlock(responseObject);
                    }
                });
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failureBlock(error);
                    NSLog(@"Error结果：%@",[NSString stringWithFormat:@"请求失败:%@\n网址:%@\n参数:%@",error.localizedDescription, urlString, paraments]);
                });
            }];
//            [kAF GET:urlString parameters:paraments progress:^(NSProgress * _Nonnull downloadProgress) {
//                if (progress) {
////                    progress()
//                }
//            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                failureBlock(error);
//                NSLog(@"Error结果：%@",[NSString stringWithFormat:@"请求失败:%@\n网址:%@\n参数:%@",error.localizedDescription, urlString, paraments]);
//                });
//            }];
            break;
        }

        case HttpRequestTypePost:
        {
            [kAF POST:urlString parameters:paraments headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if([[responseObject class] isSubclassOfClass:[NSData class]]){
                    responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                }
                NSDictionary *kDataDict = responseObject;
                NSString *err_code;
                if ([[kDataDict objectForKey:@"code"] isKindOfClass:[NSNumber class]]) {
                    err_code = [[kDataDict objectForKey:@"code"] stringValue];
                }else if([[kDataDict objectForKey:@"code"] isKindOfClass:[NSArray class]]){
                    err_code = [[kDataDict objectForKey:@"code"] firstObject];
                }else{
                    err_code = [kDataDict objectForKey:@"code"];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([err_code intValue]==400) {
                        [YYJ_MBHud hide];
//                    NSLog(@"%d"[[kDataDict objectForKey:@"data"] objectForKey:@"code"] integerValue]);
//                    [self loginOut];
                        if ([[kDataDict objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                            NSString *code = @"";
                            if ([[[kDataDict objectForKey:@"data"] objectForKey:@"code"] isKindOfClass:[NSNumber class]]) {
                                code = [[[kDataDict objectForKey:@"data"] objectForKey:@"code"] stringValue];
                            }else{
                                code = [[kDataDict objectForKey:@"data"] objectForKey:@"code"];
                            }
                            if ([code isEqualToString:@"10100"]) {
                                NSLog(@"token过期:%@",urlString);
                                [self loginOut];
                            }else if(successBlock){
                                successBlock(responseObject);
                            }
                        }else if(successBlock){
                            successBlock(responseObject);
                        }
                    }else if ([err_code intValue]==401){//需要更新
                        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"需要更新才能继续使用" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *kCancel = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            //8、itms-apps:// 开头
                            NSString *urlStr = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id%@", APPID];
                            
                            //打开链接地址
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        //                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                        }];
                        UIAlertAction *kSend = [UIAlertAction actionWithTitle:@"稍后再去" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        }];
                        [kCancel setValue:APPMianColor forKey:@"_titleTextColor"];
                        [kSend setValue:APPMianColor forKey:@"_titleTextColor"];
                        
                        [alertVc addAction:kCancel];
                        [[YYJ_PublicClass getCurrentVC] presentViewController:alertVc animated:YES completion:nil];
                    }else if(successBlock){
                        successBlock(responseObject);
                    }
                });
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                failureBlock(error);
                NSLog(@"Error结果：%@",[NSString stringWithFormat:@"请求失败:%@\n网址:%@\n参数:%@",error.localizedDescription, urlString, paraments]);
                });
            }];
//            [kAF POST:urlString parameters:paraments progress:^(NSProgress * _Nonnull uploadProgress) {
//                if(progress){
//
//                }
//
//            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                if([[responseObject class] isSubclassOfClass:[NSData class]]){
//                    responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//                }
//                NSDictionary *kDataDict = responseObject;
//                NSString *err_code;
//                if ([[kDataDict objectForKey:@"code"] isKindOfClass:[NSNumber class]]) {
//                    err_code = [[kDataDict objectForKey:@"code"] stringValue];
//                }else if([[kDataDict objectForKey:@"code"] isKindOfClass:[NSArray class]]){
//                    err_code = [[kDataDict objectForKey:@"code"] firstObject];
//                }else{
//                    err_code = [kDataDict objectForKey:@"code"];
//                }
//                dispatch_async(dispatch_get_main_queue(), ^{
//                if ([err_code intValue]==400) {
//                    [YYJ_MBHud hide];
////                    NSLog(@"%d"[[kDataDict objectForKey:@"data"] objectForKey:@"code"] integerValue]);
////                    [self loginOut];
//                    if ([[kDataDict objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
//                        if ([[[[kDataDict objectForKey:@"data"] objectForKey:@"code"] stringValue] isEqualToString:@"10100"]) {
//                            [self loginOut];
//                        }else if(successBlock){
//                            successBlock(responseObject);
//                        }
//                    }else if(successBlock){
//                        successBlock(responseObject);
//                    }
//                }else if(successBlock){
//                    successBlock(responseObject);
//                }
//                });
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                failureBlock(error);
//                NSLog(@"Error结果：%@",[NSString stringWithFormat:@"请求失败:%@\n网址:%@\n参数:%@",error.localizedDescription, urlString, paraments]);
//                });
//            }];
        }
    }
}
-(void)loginOut{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:Anda_locForKey(@"ANDA.账号需要重新验证") preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addAction:[UIAlertAction actionWithTitle:Anda_locForKey(@"ANDA.确认") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [YYJ_UserProfileModel loginOutUser];
    }]];
    [[YYJ_PublicClass getCurrentVC] presentViewController:alertVc animated:YES completion:nil];
}
#pragma mark 不上传文件的post请求用requestWithType 方法  上传未知文件的post用这个方法
-(NSURLSessionDataTask *)postRequest:(NSString *)strUrl andParameters:(id)parameters andPostData:(NSData *)data andFileName:(NSString *)fileName andMimeType:(NSString *)mimeType withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock progress:(uploadProgress)progress{
//    strUrl = [NSURL isChinese:strUrl];
    AFHTTPSessionManager * kAF =[self creatAFwithURL:strUrl];
    

    return [kAF POST:strUrl parameters:parameters headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if(data){
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:mimeType];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(progress &&  uploadProgress.completedUnitCount && uploadProgress.totalUnitCount){
                progress(uploadProgress.completedUnitCount / (float)uploadProgress.totalUnitCount);
            }
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([[responseObject class] isSubclassOfClass:[NSData class]]){
            responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if(successBlock){
                successBlock(responseObject);
            }
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(failureBlock){
                NSLog(@"%@",[NSString stringWithFormat:@"请求失败:%@__失败类型:%zd\n网址:%@\n参数:%@",error.localizedDescription, error.code, strUrl, parameters]);
                failureBlock(error);
            }
        });
    }];
}
#pragma mark - 文件下载
/**
 *  文件下载
 *
 *  @param operations   文件下载预留参数---视具体情况而定 可移除
 *  @param savePath     下载文件保存路径
 *  @param urlString    请求的url
 *  @param successBlock 下载文件成功的回调
 *  @param failureBlock 下载文件失败的回调
 *  @param progress     下载文件的进度显示
 */
-(NSURLSessionDownloadTask *)downLoadFileWithOperations:(NSDictionary *)operations withSavaPath:(NSString *)savePath withUrlString:(NSString *)urlString withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock withDownLoadProgress:(downloadProgress)progress
{
//    urlString = [NSURL isChinese:urlString];
    AFHTTPSessionManager * manager = [self creatAFwithURL:urlString];
    NSMutableURLRequest *kDownRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [kDownRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [kDownRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [kDownRequest setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"X_DEVID"];
    if ([YYJ_UserProfileModel sharedUserProfile].token.length>0) {
        [kDownRequest setValue:[YYJ_UserProfileModel sharedUserProfile].token forHTTPHeaderField:@"token"];
    }
    NSURLSessionDownloadTask* kTask = [manager downloadTaskWithRequest:kDownRequest progress:^(NSProgress * _Nonnull downloadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(progress){
                progress((float)downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            }
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        return  [NSURL fileURLWithPath:savePath];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
        if (error) {
            if(failureBlock){
                NSLog(@"%@",[NSString stringWithFormat:@"请求失败:%@__失败类型:%zd\n网址:%@\n参数:%@",error.localizedDescription, error.code, urlString, operations]);
                failureBlock(error);
            }
        }else{
            if(successBlock){
                successBlock(response);
            }
        }
        });

    }];
    [kTask resume];
    return kTask;
}
@end
